
package biblio.util;


import javax.servlet.http.*;

/**
 *
 * @author mephisto
 * This class helps in operations on Cookies.
 */
public class CookieUtility
{
    /**
     *
     * @param request
     * @param cookieName
     * @param defaultValue
     * @return a value of Cookie represented by name set in @param cookieName.
     * If this Cookie doesn't exist, method returns value set in @param defaultValue
     */  
    public static String getCookieValue (HttpServletRequest request,
            String cookieName, String defaultValue)
    {
        Cookie[] cookies = request.getCookies();
        if (cookies != null)
        {
            for(int i=0; i<cookies.length; i++)
            {
                Cookie cookie = cookies[i];
                if (cookieName.equals(cookie.getName()))
                  return(cookie.getValue());
            }
        }
        return (defaultValue);
    }

    /**
     *
     * @param request
     * @param cookieName
     * @return a Cookie object represented by @param cookieName in request. If
     * cookie won't be found, method returns null.
     */
    public static Cookie getCookie(HttpServletRequest request, String cookieName)
    {
        Cookie[] cookies = request.getCookies();
        if (cookies != null)
        {
          for(int i=0; i<cookies.length; i++)
          {
            Cookie cookie = cookies[i];
            if (cookieName.equals(cookie.getName()))
              return(cookie);
          }
        }
        return (null);
    }

    /**
     *
     * @param response object to which Cookie will be added
     * @param cookieName is the name of Cokie
     * @param cookieValue is the value of Cookie
     * @param path to set path to which Cookie refer to
     * Method add Cookie to response
     */
    public static void addCookie(HttpServletResponse response, String cookieName,
            String cookieValue, String path)
    {
        Cookie cookie = new Cookie(cookieName, cookieValue);
        //przyporzadkowanie do wszystkich adresow
        cookie.setPath(path);
        response.addCookie(cookie);
    }

    /**
     *
     * @param response object to which Cookie will be added
     * @param cookieName is the name of Cokie
     * @param cookieValue is the value of Cookie
     * path is set "/" to which Cookie refer to (it means it will be available for
     * all in the server, according to specyfication)
     * Method add Cookie to response
     */
    public static void addCookie(HttpServletResponse response, String cookieName,
            String cookieValue)
    {
        addCookie(response, cookieName, cookieValue, "/");
    }
}
